package com.liuning.Thread;

import org.apache.commons.io.FileUtils;

import java.io.File;
import java.io.IOException;
import java.net.URL;
import java.util.concurrent.*;

/**
 * 线程创建方式三：实现Callable接口
 */
public class TestCallable implements Callable<Boolean> {

    /**
     * 网络图片地址
     */
    private String url;

    /**
     * 保存的文件名
     */
    private String name;

    public TestCallable(String url,String name) {
        this.url = url;
        this.name = name;
    }

    @Override
    public Boolean call() throws Exception {
        WebDownloaderCallable downloader = new WebDownloaderCallable();
        downloader.downloader(url,name);
        System.out.println("下载了文件名为：" + name);
        return true;
    }

    public static void main(String[] args) throws ExecutionException, InterruptedException {
        //下载到当前目录
        TestCallable t1 = new TestCallable("http://47.93.247.196:8088/uploadFileServer/getFile?fileName=boy01.png", "1.jpg");
        TestCallable t2 = new TestCallable("http://47.93.247.196:8088/uploadFileServer/getFile?fileName=boy01.png", "2.jpg");
        TestCallable t3 = new TestCallable("http://47.93.247.196:8088/uploadFileServer/getFile?fileName=boy01.png", "3.jpg");

        //创建执行服务
        ExecutorService ser = Executors.newFixedThreadPool(3);

        //提交执行
        Future<Boolean> res1 = ser.submit(t1);
        Future<Boolean> res2 = ser.submit(t2);
        Future<Boolean> res3 = ser.submit(t3);

        //获取结果
        Boolean r1 = res1.get();
        Boolean r2 = res2.get();
        Boolean r3 = res3.get();
        //关闭服务
        ser.shutdownNow();
    }
}

//下载器
class WebDownloaderCallable {
    //下载方法
    public void downloader(String url,String name) {
        try {
            FileUtils.copyURLToFile(new URL(url),new File(name));
        } catch (IOException e) {
            e.printStackTrace();
            System.out.println("下载异常");
        }
    }
}
